package mephisto.rest.resources;

import java.io.InputStream;

import mephisto.model.ContentDescriptor;

import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Status;
import org.restlet.resource.InputRepresentation;
import org.restlet.resource.Representation;
import org.restlet.resource.ResourceException;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;

public class BinaryResource extends Resource {

    public BinaryResource(Context context, Request request, Response response) {
        super(context, request, response);
        //getVariants().add(new Variant(MediaType.TEXT_PLAIN));
        getVariants().add(new Variant(MediaType.IMAGE_ALL));
    }

    public Representation represent(Variant variant) throws ResourceException {

        try {
            String image = (String) getRequest().getAttributes().get("content-id");
            //String rootUri = "http://localhost:8182/";
            mephisto.Context context = new mephisto.Context();
            // getRequest().getOriginalRef().get
            ContentDescriptor descriptor = new ContentDescriptor(image);
            context.put("cdescriptor", descriptor);
            InputStream stream = mephisto.getContentService().getContentStream(image, context);
            
            getResponse().setStatus(Status.SUCCESS_OK);
            return new InputRepresentation(stream, MediaType.IMAGE_PNG);
            

        } catch (Exception e) {
            e.printStackTrace();
            getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
            return new StringRepresentation(e.getMessage(), MediaType.TEXT_PLAIN);
            

        }
    }

}
